package org.jeecg.modules.workflow.framework.activiti.core.listener;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.google.common.collect.ImmutableSet;
import lombok.extern.slf4j.Slf4j;
import org.flowable.common.engine.api.delegate.event.FlowableEngineEntityEvent;
import org.flowable.common.engine.api.delegate.event.FlowableEngineEventType;
import org.flowable.engine.HistoryService;
import org.flowable.engine.TaskService;
import org.flowable.engine.delegate.event.AbstractFlowableEngineEventListener;
import org.flowable.engine.delegate.event.FlowableActivityCancelledEvent;
import org.flowable.engine.history.HistoricActivityInstance;
import org.flowable.engine.runtime.ProcessInstance;
import org.flowable.task.api.Task;
import org.flowable.task.api.history.HistoricTaskInstance;
import org.jeecg.modules.workflow.service.task.BpmActivityService;
import org.jeecg.modules.workflow.service.task.BpmProcessInstanceService;
import org.jeecg.modules.workflow.service.task.BpmTaskService;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;
import org.springframework.transaction.support.TransactionSynchronization;
import org.springframework.transaction.support.TransactionSynchronizationManager;

import javax.annotation.Resource;
import java.util.List;
import java.util.Set;

/**
 * 监听 {@link Task} 的开始与完成，创建与更新对应的 {@link org.jeecg.modules.workflow.entity.BpmTaskExt} 记录
 *
 * @author 芋道源码
 */
@Component
@Slf4j
public class BpmTaskEventListener extends AbstractFlowableEngineEventListener {

    @Resource
    @Lazy // 解决循环依赖
    private BpmTaskService bpmTaskService;

    @Resource
    @Lazy // 解决循环依赖
    private BpmActivityService activityService;

    @Resource
    @Lazy
    private HistoryService historyService;

    @Resource
    @Lazy
    private TaskService taskService;

    @Resource
    @Lazy // 解决循环依赖
    private BpmProcessInstanceService processInstanceService;


    public static final Set<FlowableEngineEventType> TASK_EVENTS = ImmutableSet.<FlowableEngineEventType>builder()
            .add(FlowableEngineEventType.TASK_CREATED)
            .add(FlowableEngineEventType.TASK_ASSIGNED)
            .add(FlowableEngineEventType.TASK_COMPLETED)
            .add(FlowableEngineEventType.ACTIVITY_CANCELLED)
            .build();

    public BpmTaskEventListener(){
        super(TASK_EVENTS);
    }

    @Override
    protected void taskCreated(FlowableEngineEntityEvent event) {
        Task task = (Task) event.getEntity();
        bpmTaskService.createTaskExt(task);

        TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() {

            @Override
            public void afterCommit() {
                // 获得任务列表
                List<HistoricTaskInstance> tasks = historyService.createHistoricTaskInstanceQuery()
                        .processInstanceId(task.getProcessInstanceId())
                        .orderByHistoricTaskInstanceStartTime().desc() // 创建时间倒序
                        .list();
                //如果是第一个用户节点,并且审批人和发起人相同，那么自动审批通过
                if (CollUtil.isNotEmpty(tasks) && 1 == tasks.size()) {
                    ProcessInstance instance = processInstanceService.getProcessInstance(task.getProcessInstanceId());
                    if (instance != null) {
                        if (instance.getStartUserId().equals(task.getAssignee())) {
                            taskService.addComment(task.getId(), instance.getProcessInstanceId(), "发起流程");
                            taskService.complete(task.getId(), instance.getProcessVariables());
                        }
                    }

                }
            }
        });


    }

    @Override
    protected void taskCompleted(FlowableEngineEntityEvent event) {
        bpmTaskService.updateTaskExtComplete((Task)event.getEntity());
    }

    @Override
    protected void taskAssigned(FlowableEngineEntityEvent event) {
        bpmTaskService.updateTaskExtAssign((Task)event.getEntity());
    }

    @Override
    protected void activityCancelled(FlowableActivityCancelledEvent event) {
        List<HistoricActivityInstance> activityList = activityService.getHistoricActivityListByExecutionId(event.getExecutionId());
        if (CollUtil.isEmpty(activityList)) {
            log.error("[activityCancelled][使用 executionId({}) 查找不到对应的活动实例]", event.getExecutionId());
            return;
        }
        // 遍历处理
        activityList.forEach(activity -> {
            if (StrUtil.isEmpty(activity.getTaskId())) {
                return;
            }
            bpmTaskService.updateTaskExtCancel(activity.getTaskId());
        });
    }

}
